@echo off
rem Sample script to GPG2 and push a file via WinSCP
rem File to encrypt and push is in the outgoing folder
rem Files plus their gpg2 encrypted equivalents will be moved to processed file upon successful upload

rem SCP host details
set HOSTNAME=<SFTP Server>
set USERNAME=<SFTP Username>
set PASSWORD=<SFTP Password>
set KEY_FILENAME=ssh_private_key.ppk

rem Directory to push file to
set INCOMING_FOLDER_NAME=<Incoming Folder>
rem Directory to place file and gpg2 after successful push
set PROCESSED_FOLDER_NAME=<Processed Folder>
rem Directory of files to be pushed
set OUTGOING_FOLDER_NAME=<Outgoing Folder>

rem Winscp directory
set WINSCP_INSTALL_DIR=c:\program files (x86)\winscp

rem GPG2 path, recipient to encrypt for, recipient id and local id
set GPG2_INSTALL_DIR=c:\program files(x86)\GNU\GnuPG
set GPG2_RECIPIENT_ID=<Recipient Id>
set GPG2_LOCAL_USER_ID=<Local User Id>

rem Loop through each file in the folder
for %%f in (%OUTGOING_FOLDER_NAME%\*.*) do (

	echo uploading %%~nf%%~xf
		
	rem PGP the file
	"%gpg2_install_dir%\gpg2" --compress-algo 1 --cipher-algo cast5 --passphrase-fd 0 --armor --recipient %gpg2_recipient_id% --local-user %gpg2_local_user_id% --output "%OUTGOING_FOLDER_NAME%\%%~nf%%~xf.gpg2" -se "%OUTGOING_FOLDER_NAME%\%%~nf%%~xf" < "%gpg2_install_dir%\password.txt"

	rem create the WinSCP script with it set in batch mode so it does not prompt for input
	echo option batch on >> script.cmd
	echo option confirm off >> script.cmd
	echo echo on >> script.cmd
	rem SFTP the file
	echo open sftp://%USERNAME%:%PASSWORD%@%HOSTNAME% >> script.cmd
	echo cd %INCOMING_FOLDER_NAME% >> script.cmd
	rem Use this line to push a file and its trigger
	echo put %OUTGOING_FOLDER_NAME%\%%~nf%%~xf.gpg2 >> script.cmd
	echo lcd %PROCESSED_FOLDER_NAME% >> script.cmd
	echo get %%~nf%%~xf.gpg2 >> script.cmd
	rem Close the connection and exit
	echo close >> script.cmd
	echo exit >> script.cmd
	if exist %OUTGOING_FOLDER_NAME%\%%~nf%%~xf "%winscp_install_dir%\winscp.com" /privatekey="%winscp_install_dir%\%KEY_FILENAME%"  /script=script.cmd

	if exist %PROCESSED_FOLDER_NAME%\%%~nf%%~xf.gpg2 (
		if not %PROCESSED_FOLDER_NAME% == %OUTGOING_FOLDER_NAME% (
			copy %OUTGOING_FOLDER_NAME%\%%~nf%%~xf %PROCESSED_FOLDER_NAME%\%%~nf%%~xf
			del %OUTGOING_FOLDER_NAME%\%%~nf%%~xf
			del %OUTGOING_FOLDER_NAME%\%%~nf%%~xf.gpg2
		)
	)

	del script.cmd
)
